/**
 * 
 */
package ch.iec.tc57._2011.meterreadschedules.impl;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.sql.DataSource;
import javax.xml.ws.Holder;

import ch.iec.tc57._2011.getmeterreadschedulesmessage.GetMeterReadSchedulesRequestType;
import ch.iec.tc57._2011.getmeterreadschedulesmessage.MeterReadSchedulesPayloadType;
import ch.iec.tc57._2011.meterreadschedules.FaultMessage;
import ch.iec.tc57._2011.meterreadschedules.GetMeterReadSchedulesPort;
import ch.iec.tc57._2011.schema.message.HeaderType;
import ch.iec.tc57._2011.schema.message.ReplyType;
import ch.iec.tc57._2011.schema.message.UserType;

import com.primestone.cim.Completer;
import com.primestone.cim.util.DateUtil;
import com.primestone.cim.util.RandomUtil;
import com.primestone.cim.util.StringUtil;
import com.primestone.cim.util.enums.CIMNoun;
import com.primestone.cim.util.enums.CIMVerb;

/**
 * @author cesar.mateus
 *
 */
@Stateless
@WebService
public class GetMeterReadSchedulesPortImpl implements GetMeterReadSchedulesPort {

	@Resource(name="java:/cimsqlserverds")
	DataSource dataSource;
	
	@Override
	public void getMeterReadSchedules(Holder<HeaderType> header,
			GetMeterReadSchedulesRequestType request,
			Holder<MeterReadSchedulesPayloadType> payload,
			Holder<ReplyType> reply) throws FaultMessage {
		try {
			// Setting header
			header.value = constructGetMeterReadScheduleHeader();

			// Extract useful values from request and use it.
			MeterReadSchedulesPayloadType meterReadSchedulesPayloadType = new MeterReadSchedulesPayloadType();
			meterReadSchedulesPayloadType.setMeterReadSchedules(Completer.fillMeterReadSchedules(request));

			payload.value = meterReadSchedulesPayloadType;


			ReplyType replyType = new ReplyType();
			replyType.setResult("OK");
			reply.value = replyType;	
		} catch (Exception e) {
			e.printStackTrace();
			// TODO Usar el constructor de FaultMessage: que recibe un objeto MeterReadingsFaultMessageType
			throw new FaultMessage(e.getCause() + ": " + e.getMessage());
		}
	}
	
	private static HeaderType constructGetMeterReadScheduleHeader() {
		HeaderType headerType = new HeaderType();
		headerType.setVerb(CIMVerb.GET_VERB.getVerb());
		headerType.setNoun(CIMNoun.METER_READ_SCHEDULE_NOUN.getNoun());
		headerType.setRevision(StringUtil.DEFAULT_REVISION);
		headerType.setContext(StringUtil.TESTING_CONTEXT);

		headerType.setTimestamp(DateUtil.getXMLGregorianCalendarFromGregorianCalendar());

		headerType.setSource(StringUtil.SOURCE);
		headerType.setMessageID(RandomUtil.nextString());

		UserType userType = new UserType();
		userType.setUserID("Test");
		userType.setOrganization(StringUtil.ORGANIZATION);

		headerType.setUser(userType);

		return headerType;
	}

}
